'''
Created on Jun 12, 2010

@author: oabalbin
'''
import os
import glob
from optparse import OptionParser
from collections import defaultdict

import interactome.parsers.string_tables as pr
import interactome.databases.tables as mt

def table_descriptions():
    """
    It returns the table descriptions for the STRING database
    """
    
    descriptions = {'protein_aliases':'species_ncbi_taxon_id VARCHAR(100), protein_id VARCHAR(100), alias VARCHAR(500), source VARCHAR(100), INDEX proteinid (protein_id), INDEX myalias (alias)',
                    'protein_links_detailed':'item_id_a VARCHAR(100), item_id_b VARCHAR(100), neighborhood SMALLINT, fusion SMALLINT,  cooccurence SMALLINT,' +
                    'coexpression SMALLINT, experimental SMALLINT, indatabase SMALLINT, textmining SMALLINT, combined_score SMALLINT, INDEX itemA (item_id_a), INDEX itemB (item_id_b), INDEX combinedscore (combined_score)',
                    'protein_links':'item_id_a VARCHAR(100), item_id_b VARCHAR(100), combined_score SMALLINT, INDEX itemA (item_id_a), INDEX itemB (item_id_b), INDEX combinedscore (combined_score)',
                    'protein_actions_detailed':'item_id_a VARCHAR(100), item_id_b VARCHAR(100), mode  VARCHAR(100), action  VARCHAR(100),  a_is_acting SMALLINT, score SMALLINT,  sources VARCHAR(100), transferred_sources VARCHAR(200),'+
                    'INDEX itemA (item_id_a), INDEX itemB (item_id_b), INDEX myscore (score), INDEX source (sources)',
                    'protein_actions':'item_id_a VARCHAR(100), item_id_b VARCHAR(100), mode  VARCHAR(100), action  VARCHAR(100),  a_is_acting SMALLINT, score SMALLINT,'+
                    'INDEX itemA (item_id_a), INDEX itemB (item_id_b), INDEX myscore (score)'
                    }
    
    return descriptions



def read_files_folder(folderpath,ext):
    ''' '''
    # Read files in folder
    myfiles=[]
    for infile in glob.glob( os.path.join(folderpath, '*'+ext) ):
        myfiles.append(infile)
        #print "current file is: " + infile
    return myfiles
    

def processes_database_files(myfiles):
    """
    the process of the files depend on the type of file your are passing    
    """
    dbf=defaultdict()
    
    
    for f in myfiles:
        f1 = f.split('/')[-1]
        of=f+'_dbfile'
        f1file, offile = open(f),open(of,'w')
        
        if f1.find('protein.aliases.') != -1:
            pr.parse_STRING_protein_alias(f1file, offile)
            dbf[of] = 'protein_aliases'
            
        elif f1.find('protein.links.detailed.') != -1:
            pr.parse_STRING_protein_links_detailed(f1file, offile)
            dbf[of] = 'protein_links_detailed'
        
        elif f1.find('protein.links.') != -1:
            pr.parse_STRING_protein_links(f1file, offile)
            dbf[of] = 'protein_links'
            
        elif f1.find('protein.actions.detailed.') != -1:
            pr.parse_STRING_protein_actions_detailed(f1file, offile)
            dbf[of] = 'protein_actions_detailed'
            
        elif f1.find('protein.actions.') != -1:
            pr.parse_STRING_protein_actions(f1file, offile)
            dbf[of] = 'protein_actions'
            
    
    return dbf
    
    
def create_database(mt,dbfiles, doit=False):
    """
    It creates a databases if doit = True
    """
    tables_header = table_descriptions()
    
    if doit:
        print 'Making tables'            
        for dbf, tableName in dbfiles.iteritems():
            tableDescription = tables_header[tableName]
            #print tableDescription
            if not(mt.table_existence(tableName)):
                mt.create_table(tableName,tableDescription)
                
            mt.load_data_table(tableName,dbf)

  
def initialize_database(myfiles, mytables, doit=False):
    
    dbfiles = processes_database_files(myfiles)
    create_database(mytables, dbfiles,doit)
    


if __name__ == '__main__':
    
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-f", "--folder", dest="folder",
                            help="database input folder for all files to use")
    
    (options, args) = optionparser.parse_args()
    ext='.txt'
    dbtrue=True
    
    myfiles = read_files_folder(options.folder,ext)
    dbhost, dbuser, dbpasswd, database = "localhost", "oabalbin", "oscar", "STRING8"
    mytables = mt.tables(dbhost, dbuser, dbpasswd, database)
    initialize_database(myfiles, mytables, dbtrue)











